#导入模块
from datetime import date
from posixpath import join
import re
from types import resolve_bases
from typing_extensions import ParamSpecArgs #蓝图模块
from flask import Blueprint,request
from flask.helpers import total_seconds
from requests.api import post
from werkzeug import datastructures #导入request
from db import db1  
from flask.json import jsonify
import json #导入json

#实例化
bp_coures = Blueprint("course",__name__)

#接口
#                  接口               添加   获取   修改    删除
@bp_coures.route('/couponM',methods=["POST","GET","PUT","DELETE"])
def couponM():
    #添加
    if request.method == "POST":
        #获取用户输入
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
         #构造sql语句
        sql ="insert into coupon values(0,'%s',%d,'%s','%s')"%(data['name'],int(data['total']),data['stime'],data['etime'])
        #pymysql
        db1.insert(sql)
        #返回结果
        return 'ok'
    #获取    
    elif request.method == 'GET':
        #根据id获取信息
        id = request.args.get('id')
        sql = "select * from coupon where id=%d" % (int(id))#id属于强转int类型
        res = db1.find(sql)
        return jsonify({"code":200,'coupon':res})
    #修改
    elif request.method == 'PUT':
        #获取用户输入
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        #构造sql语句  update 表名 set 字段名1=值  where id=1
        sql = "update coupon set name='%s',total=%d,starttime='%s',endtime='%s' where id=%d"%(data['name'],int(data['total']),data['stime'],data['etime'],int(data['id']))
        db1.insert(sql)
        return jsonify({"code":200})
    #删除
    elif request.method  == 'DELETE':
        id = request.args.get('id')
        sql ="delete from coupon where id=%d" %(int(id))
        db1.insert(sql)
        return jsonify({"code":200})


def get_data():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form  
    return data    

# #管理部门
# @bp_coures.route('/deptM',methods=['POST','GET'])
# def deptM():
#     if request.method == "POST":
#         data = get_data()
#         #判断名字是否已经存在
#         sql = "select id from dept where name='%s'"%(data['name'])
#         res = db1.find(sql)
#         #存在直接返回
#         if res:
#             return jsonify({"code":10011,'mes':'已经存在'})
#         #不存在添加
#         else:
#             sql = "insert into dept(name) values('%s')"%(data['name'])
#             db1.insert(sql)
#             return jsonify({"code":200})
#     else:
#         sql = "select * from dept"
#         res = db1.findall(sql)
#         return jsonify({"code":200,'list':res})
    
#  #人员部门
# @bp_coures.route('/empM',methods=["POST","GET"])
# def empM():
#     if request.method == "POST":
#         data = get_data()
#         #添加员工
#         sql = "insert into emp values(0,'%s',%d,%.2f,%d)"%(data['name'],int(data['sex']),float(data['salsry']),int(data['dept_id']))
#         db1.insert(sql)
#         #更新部门表员工总数
#         sql1 = 'select total from dept where id=%d'%int(data['dept_id'])
#         res = db1.find(sql1)
#         total = int(res['total'])+1
#         sql2 = 'update dept set total=%d where id=%d'%(total,int(data['dept_id']))
#         db1.insert(sql2)
#         return jsonify({"code":200})
    
#     else:
#         pass
from utils.myfile import myfile
import os
# #文件上传
# @bp_coures.route('/upload',methods=['POST'])
# def upload():
#     #获取文件
#     file = request.files['file']
#     #选择文件夹
#     #创建文件夹
#     myfile.file_mkdir(2)
#     #保存文件
#     file.save(os.path.join('./static/upload/2/',file.filename))
#     #保存 /static/upload/1/
#     return 'ok'

#景点操作接口
@bp_coures.route('/scenicm',methods=['POST','GET'])
def scenicm():
    if request.method == "POST":
        #图片上传，vue封装formdata
        data = request.form
        #添加景点   
        sql = "insert into scenic(title,price,typeid) values('%s',%.2f,%d)"%(data['title'],float(data['price']),int(data['typeid']))
        db1.insert(sql)
        #获取新加的id
        sql1 = "select id from scenic where title='%s'"%(data['title'])
        res = db1.find(sql1)
        #文件上传，上传成功后图片路径
        file = request.files['file']
      
        myfile.file_mkdir(str(res['id']))
        file.save(os.path.join('./static/upload/'+str(res['id']),file.filename))
        #组装数据添加
        sql3 = "update scenic set pic='%s' where id=%d"%('/static/upload/'+str(res['id'])+"/"+file.filename,int(res['id']))
        db1.insert(sql3)
        return jsonify({"code":200})
        
    else:
        cityid = request.args.get('cityid')
        if cityid == '0':
            sql ="select * from product"
        else:
            sql = "select *from product where city_id=%d"%(int(cityid))
            res =db1.findall(sql)
            return jsonify({"code":200,'list':res})
        
        
        # sql = 'select * from scenic'
        # res = db1.findall(sql)
        # return jsonify({"code":200,'list':res})
    
#文件上传
@bp_coures.route('/upload',methods=['POST'])
def upload():
    file = request.files['file']
    cityid = request.form['cityid']
    #创建文件夹
    myfile.file_mkdir(cityid)
    #图片上传 
    file.save(os.path.join('./static/upload/'+str(cityid),file.filename))
    return jsonify({"code":200,'url':'/static/upload/'+str(cityid)+'/'+file.filename})

#查询所有景区
@bp_coures.route('/citym')
def citym():
    sql = "select id,name from city"
    res = db1.findall(sql)
    return jsonify({"code":200,'list':res})

#添加商品接口
@bp_coures.route('/prom',methods=['POST'])
def prom():
   data = get_data()
   sql = "insert into product(title,price,city_id,pic) values('%s',%.2f,%d,'%s')"%(data['title'],float(data['price']),int(data['city_id']),data['pic'])
   db1.insert(sql)
   return jsonify({"code":200})



# @bp_coures.route('/recordM')
# def recordM():
#     #获取id
#     id = request.args.get('typeid')
#     if id== '0':
#         sql = 'select * from record'
#     else:
#         sql = 'select * from record where typeid=%d' %(int(id))
#     res = db1.findall(sql)
#     list = []
#     for i in res:
#         dict = {'id':i['id'],'stime':datetime.datetime.strftime(i['stime'],'%y-%m-%d'),'etime':datetime.datetime.strftime(i['etime'],'%y-%m-%d'),'money':float(i['money'])}
#         list.append(dict)
#     return jsonify({"code":200,'list':list})
    


# @bp_coures.route('/detailM')
# def detailM():
#     id = request.args.get('id')
#     sql = "select * from record where id = %d"%(int(id))
#     res = db1.find(sql)
#     record = {'id':res['id','stime':datetime.datetime.strftime(res['stime'],'%y-%m-%d'),'money':float(res['money'])]}
#     return jsonify({"code":200,'record':record})

# #获取分类接口
# @bp_coures.route('/orderMe')
# def orderMe():
#     sql = 'select * from ordes'
#     res = db1.findall(sql)
#     return jsonify({"code":200,'list':res})

# #获取订单接口       
# @bp_coures.route('/orderMs')
# def orderMs():
#     sql = 'select * from orders'
#     res = db1.findall(sql)
#     return jsonify({"code":200,'list':res})

# #获取分类接口
# @bp_coures.route('/orderM',methods=['GET','PUT'])
# def orderM():
#     if request.method == "PUT":
#         id = request.args.get('id')
#         sql = "select * from orders where id=%d"%(int(id))
#         res = db1.find(sql)
#         #判断状态原来为1改成2，原来为2改成1
#         status = 2
#         if int(res['status']) == 2:
#             status=1            
        
#         #执行更新操作
#         sql1 = "update orders set status=%d where id=%d"%(status,int(id))
#         db1.insert(sql1)
#         return jsonify({"code":200})

#     else:
#         #当前页
#         page = int(request.args.get('page'))
#         #每页显示多少条
#         page_size = int(request.args.get('page_size'))
#         start = (page-1)*page_size
#         sql = 'select * from orders limit %d,%d'%(start,page_size)
#         res = db1.findall(sql)
#         #总条数
#         sql1 = "select count(id) from orders"
#         res1 = db1.find(sql1)
#         return jsonify({"code":200,'list':res,'total':res1['count(id)']})

#发红包200-0.01区间接口
@bp_coures.route('/sendmoney')
def sendmoney():
    money = request.args.get('money')
    #对数据进行有效性验证
    if not money:
        return jsonify({"code":10010,"mes":'请输入金额'})
    else:
        try:
             #格式验证
             money = float(money)
        except:
            return jsonify({'code':10012,'mes':'格式有误'})
    if money<200 and money>0.01:
        return jsonify({"code":200})
    else:
        return jsonify({"code":10012})   
#发红包200-0.01区间接口
# @bp_coures.route('/sendmoney')
# def sendmoney():
#     money = request.args.get('money')
#     #对数据进行有效性验证
#     if not money:
#         return jsonify({"code":10010,"mes":'请输入金额'})
#     else:
#         try:
#         #格式验证
#             money = float(money)
#         except:
#             return jsonify({'code':10012,'mes':'格式有误'})
#     if money<200 and money>0.01:
#             return jsonify({"code":200})
#     else:
#             return jsonify({"code":10012})


#添加测试用例接口
@bp_coures.route('/sendMony',methods=['POST'])
def  sendMony():
    data = get_data() 
    sql = "insert into test_record(name,url,method,params,result) values('%s','%s','%s','%s','%s')"%(data['name'],data['url'],data['method'],data['params'],data['result'])
    db1.insert(sql)
    return jsonify({"code":200})

# #读取表测试以及生成报告
# import datetime
# import requests
# @bp_coures.route('/test_sendMoney',methods=['POST'])
# def test_sendMoney():
#     #读取数据库
#     sql = "select * from test_record where status=1"
#     res = db1.findall(sql)
#     list=[]
#     for i in res:
#         flag = "失败"
#         params = json.loads(i['params'])
#         if i['method'] == "get":
#             mes = requests.get(i['url'],params=params)
#         elif i['method'] == "post":
#             mes = requests.post(i['url'],data=params)
#         mm = json.loads(mes.text)
#         if mm['code'] == int(i['result']):
#             flag='成功'
#         str={"name":i['name'],"请求地址":i['url'],"返回信息":mes.text,"测试结果":flag}
#         list.append(str)
#         filename = datetime.datetime.strftime(datetime.datetime.now(),'%Y%m%d')
#         with open(os.path.join('./logs/'+filename+'.txt'),'w') as f:
#             f.write(json.dumps(list,ensure_ascii=False))
   
#     return jsonify({"code":200})